<?php
if(!defined('IN_WOGU')) {
    exit('Access Denied');
}

function new_htmlspecialchars($string) {
    return is_array($string) ? array_map('new_htmlspecialchars', $string) : htmlspecialchars($string, ENT_QUOTES);
}

function new_addslashes($string){
    if(!is_array($string)) return addslashes($string);
    foreach($string as $key => $val) $string[$key] = new_addslashes($val);
    return $string;
}

function new_stripslashes($string) {
    if(!is_array($string)) return stripslashes($string);
    foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
    return $string;
}

function trim_textarea($string) {
    $string = nl2br ( str_replace ( ' ', '&nbsp;', $string ) );
    return $string;
}

function pages($connid, $sql, $page, $perpage, $order = '', $urlrule = '', $key = '') {
    preg_match_all('/SELECT(.+)(FROM [^ ]+)(.*)/i', $sql, $matches);
    $countSql = 'SELECT COUNT(*) ' . $matches[2][0] . $matches[3][0];
    $query = mysql_query($countSql, $connid);
    $r = mysql_fetch_row($query);
    $total = $r[0];

    $destSql = $key == '' ? $sql : ('SELECT' . $matches[1][0] . $matches[2][0] . ' inner join (SELECT ' . $key . ' ' . $matches[2][0] . $matches[3][0]);
    if(!empty($order)) {
        $destSql .= ' ORDER BY ' . $order;
    }
    $destSql .= ' LIMIT '. ($page - 1) * $perpage . ',' . $perpage;
    if($key != '')
        $destSql .= ') as t using(' . $key . ')';

    $query = mysql_query($destSql, $connid);
    $items = array();
    while($r = mysql_fetch_array($query, MYSQL_ASSOC)) {
        $items[] = $r;
    }

    $pages = new Pages($page, $total, $perpage);
    if($urlrule) {
        $pages->setTags(array(
            'core'       => '<a href="'. $urlrule .'" class="%class">%page</a>',
            'prePage'    => '<div class="%class"><a href="'. $urlrule .'">上一页</a></div>',
            'nextPage'   => '<div class="%class"><a href="'. $urlrule .'">下一页</a></div>',
            'jumper'     => '<div class="%class"><input type="text" id="jumper"><input type="button" value="跳转" onclick="window.navigate(\''. rtrim($urlrule, '%page') .'\' + document.getElementById(\'jumper\').value)"></div>',
        ));
    }
    $pages ->createPrePage()->createCore()->createNextPage();
    $output = $pages->output();

    return array(
        'items' => $items,
        'pages' => $output
    );
}

function ip() {
    if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $ip = getenv('REMOTE_ADDR');
    } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
}

function str_cut($string, $length, $dot = '...') {
    $strlen = strlen($string);
    if($strlen <= $length) return $string;
    $string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '“', '”', '―', '<', '>', '・', '…'), $string);
    $strcut = '';
    if(strtolower(CHARSET) == 'utf-8') {
        $length = intval($length-strlen($dot)-$length/3);
        $n = $tn = $noc = 0;
        while($n < strlen($string)) {
            $t = ord($string[$n]);
            if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                $tn = 1; $n++; $noc++;
            } elseif(194 <= $t && $t <= 223) {
                $tn = 2; $n += 2; $noc += 2;
            } elseif(224 <= $t && $t <= 239) {
                $tn = 3; $n += 3; $noc += 2;
            } elseif(240 <= $t && $t <= 247) {
                $tn = 4; $n += 4; $noc += 2;
            } elseif(248 <= $t && $t <= 251) {
                $tn = 5; $n += 5; $noc += 2;
            } elseif($t == 252 || $t == 253) {
                $tn = 6; $n += 6; $noc += 2;
            } else {
                $n++;
            }
            if($noc >= $length) {
                break;
            }
        }
        if($noc > $length) {
            $n -= $tn;
        }
        $strcut = substr($string, 0, $n);
        $strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '―', '<', '>', '・', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
    } else {
        $dotlen = strlen($dot);
        $maxi = $length - $dotlen - 1;
        $current_str = '';
        $search_arr = array('&',' ', '"', "'", '“', '”', '―', '<', '>', '・', '…','∵');
        $replace_arr = array('&amp;','&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;',' ');
        $search_flip = array_flip($search_arr);
        for ($i = 0; $i < $maxi; $i++) {
            $current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
            if (in_array($current_str, $search_arr)) {
                $key = $search_flip[$current_str];
                $current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
            }
            $strcut .= $current_str;
        }
    }
    return $strcut.$dot;
}

function random($length, $chars = '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ') {
    $hash = '';
    $max = strlen($chars) - 1;
    for($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

function sizecount($filesize) {
    if ($filesize >= 1073741824) {
        $filesize = round($filesize / 1073741824 * 100) / 100 .' GB';
    } elseif ($filesize >= 1048576) {
        $filesize = round($filesize / 1048576 * 100) / 100 .' MB';
    } elseif($filesize >= 1024) {
        $filesize = round($filesize / 1024 * 100) / 100 . ' KB';
    } else {
        $filesize = $filesize.' Bytes';
    }
    return $filesize;
}

function sys_auth($string, $operation = 'ENCODE', $key = '', $expiry = 0) {
    $key_length = 4;
    $key = md5($key != '' ? $key : AUTH_KEY);
    $fixedkey = md5($key);
    $egiskeys = md5(substr($fixedkey, 16, 16));
    $runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : ''; 
    $keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
    $string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));
    
    $i = 0; $result = '';
    $string_length = strlen($string);
    for ($i = 0; $i < $string_length; $i++){
        $result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));
    }
    if($operation == 'ENCODE') {
        return $runtokey . str_replace('=', '', base64_encode($result));
    } else {
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    }
}

function is_email($email) {
    return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

function is_password($password) {
    $strlen = strlen($password);
    if($strlen >= 6 && $strlen <= 20) return true;
    return false;
}

function is_badword($string) {
    $badwords = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n","#");
    foreach($badwords as $value){
        if(strpos($string, $value) !== FALSE) {
            return TRUE;
        }
    }
    return FALSE;
}

function is_username($username) {
    $strlen = strlen($username);
    if(is_badword($username) || !preg_match("/^[a-zA-Z0-9_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+$/", $username)){
        return false;
    } elseif ( 20 < $strlen || $strlen < 2 ) {
        return false;
    }
    return true;
}

function is_ip($ip) {
    return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $ip);
}

function set_cookie($var, $value = '', $time = 0) {
    $time = $time > 0 ? $time : ($value == '' ? SYS_TIME - 3600 : 0);
    $s = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
    $var = COOKIE_PRE . $var;
    $_COOKIE[$var] = $value;
    if (is_array($value)) {
        foreach($value as $k=>$v) {
            setcookie($var.'['.$k.']', $v, $time, COOKIE_PATH, COOKIE_DOMAIN, $s);
        }
    } else {
        setcookie($var, $value, $time, COOKIE_PATH, COOKIE_DOMAIN, $s);
    }
}

function get_cookie($var, $default = '') {
    $var = COOKIE_PRE.$var;
    return isset($_COOKIE[$var]) ? $_COOKIE[$var] : $default;
}

function showmessage($msg, $url_forward = 'goback', $ms = 1250) {
    $view = Register::get('View', 'WOGU_SYS');
    if(!$view) {
        Loader::loadClass('View');
        $view = new View();
    }
    $view->assign('charset', CHARSET);
    $view->assign('msg', $msg);
    $view->assign('url_forward', $url_forward);
    $view->assign('ms', $ms);
    $view->display('showmessage', 'wogu');
    exit;
}

function redirect($url) {
    header('LOCATION: ' . $url);
}

function template($file, $vars = array(), $mod = 'wogu') {
    $view = Register::get('View', 'WOGU_SYS');
    if(!$view) {
        Loader::loadClass('View');
        $view = new View();
    }
    $view->assign($vars);
    $view->display($file, $mod);
}

function create_dir($path, $mode = 0777) {
    if(!is_dir($path)) {
        create_dir(dirname($path));
        mkdir($path, $mode);
        chmod($path, $mode);
    }
}

function cache_write($name, $value, $expire = 0) {
    if(is_array($value)) {
        $value = var_export($value, true);    
    }
    
    $filename = LIB_ROOT . 'data/cache/' . $name . '.php';
    $data = '<?php'."\n";
    if($expire > 0) {
        $data .= 'if(time()>' . (SYS_TIME + $expire) . ')return false;' . "\n";
    }
    $data .= 'return ' . $value . ';'."\n".'?>';
    file_put_contents($filename, $data);
    chmod($filename, 0777);
}

function cache_read($name) {
    $filename = LIB_ROOT . 'data/cache/' . $name . '.php';
    
    if(!file_exists($filename)) {
        return false;    
    }
    
    return include $filename;
}

function cache_write_ex($name, $value, $expire = 0) {
    if(is_array($value)) {
        $value = var_export($value, true);
    }
    
    $names = explode('_', $name);
    $namelast = array_pop($names);
    $dir = LIB_ROOT . 'data/cache/' . (empty($names) ? '' : implode('/', $names) . '/');
    $filename = $dir . $namelast . '.php';
    if(!is_dir($dir)) {
        create_dir($dir);
    }
    
    $data = '<?php'."\n";
    if($expire > 0) {
        $data .= 'if(time()>' . (SYS_TIME + $expire) . ')return false;' . "\n";
    }
    $data .= 'return ' . $value . ';'."\n".'?>';
    file_put_contents($filename, $data);
    chmod($filename, 0777);
}

function cache_read_ex($name) {
    $names = explode('_', $name);
    $filename = LIB_ROOT . 'data/cache/' . implode('/', $names) . '.php';

    if(!file_exists($filename)) {
        return false;    
    }
    
    return include $filename;
}

function times33($str) {
    $len = strlen($str);
    $code = 0;
    for($i = 0; $i < $len; $i++) {
        $code = (int) (($code * 33) + ord($str{$i})) & 0x7fffffff;
    }
    
    return $code;
}

function get_group_cache() {
    $cachefile = 'groups';
    $groups = cache_read($cachefile);
    if(!$groups) {
        $group = Loader::loadUserModel('GroupModel', true);
        $groups = $group->getGroups();
        cache_write($cachefile, $groups);
    }

    return $groups;
}

function password($password, $salt) {
    return md5($salt . $password);
}

function fileext($filename) {
    return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}

function get_block_cache($id, $block = null) {
    $cachename = 'block_' . $id;
    $data = cache_read_ex($cachename);
    if(!$data) {
        if(!$block) {
            $block = Register::get('block');
            if(!$block) {
                $block = Loader::loadUserModel('BlockModel', true, 'admin');
                Register::set('block', $block);
            }
        }
        
        $data = $block->getBlock(array('id' => $id));
        if($data) {
            cache_write_ex($cachename, $data);
        }
    }
    
    return $data;
}

function get_block_data_cache($id) {
    $data = get_block_cache($id);
    return $data['block_data'];
}

function geturl($path) {
    return SITE_DOMAIN . ltrim($path, '/');
}